<template>
  <view class="invoice">
    <view v-if="afterSalDetail !== null" class="after_top">
      <view class="after_top_tips">
        <view class="after_top_tips_status">
          {{ afterSalDetail.afterSaleStatusName }}
        </view>
        <view>
          {{ afterSalDetail.updateTime }}
        </view>
      </view>
    </view>
    <view class="order_info">
      <view class="order_img">
        <image class="img" :src="selectProduct.productSquareUrl" />
      </view>
      <view>
        <view class="order_number">
          <span>订单编号：</span>
          <span>{{ orderDetail.orderNo }}</span>
        </view>
        <view>
          <span>订单金额：</span>
          <span>￥ <span class="money">{{ selectProduct.payAmount }}</span></span>
        </view>
        <view v-if="afterSaleStatus === 9" class="after_logistics">
          <view class="my-orders-shop-item-control-btn gray" @tap="onLookLogistics(afterSalDetail)">查看物流
          </view>
          <view class="my-orders-shop-item-control-btn red" @tap="onUpdateOrder(afterSalDetail)">确认收货
          </view>
        </view>
      </view>
    </view>
    <view v-if="afterSalDetail === null">
      <view class="order_info">
        <view class="flex">
          申请原因：
          <uni-data-select style="margin-right: 20rpx;min-width: 160rpx;" class="left_input" @change="invoiceTypeChange"
            :clear="false" v-model="afterSaleType" :localdata="range"></uni-data-select>
        </view>
        <view class="flex">
          是否收到货：
          <uni-data-select style="margin-right: 20rpx;min-width: 130rpx;" class="left_input" @change="invoiceTypeChange"
            :clear="false" v-model="afterSaleGoodStatus" :localdata="range1"></uni-data-select>
        </view>
      </view>
      <view class="order_info" style="display: block;">
        <textarea placeholder="补充描述，有助于商家更好的处理售后问题。" class="textarea" v-model="remark"></textarea>
        <uni-file-picker limit="9" v-model="images" :auto-upload="false" file-mediatype="image" mode="grid"
          fileMediatype="image" @select="(res) => handleSelect(res)" @delete="(err) => handleDelete(err)">
          <image class="add_pic" src='../../static/img/common/add_pic.png' />
        </uni-file-picker>
      </view>
    </view>
    <view v-else class="order_info" style="display: block;">
      <view class="flex">
        售后类型：{{ afterSalDetail.afterSaleTypeName }}
      </view>
      <!-- <view class="flex">
        售后单状态：{{ afterSalDetail.afterSaleStatusName }}
      </view> -->
      <view class="flex">
        售后原因：{{ afterSalDetail.remark }}
      </view>
      <view class="flex">
        申请时间：{{ afterSalDetail.createTime }}
      </view>
      <view class="flex">
        售后编号：{{ afterSalDetail.afterSaleNo }}
      </view>
      <view v-if="afterSalDetailImages.length !== 0" class="flex">
        <image v-for="item in afterSalDetailImages" :key="item" class="after_pic" :src='item' />
      </view>
      <view class="flex" v-if="afterSaleStatus === 2 || afterSaleStatus === 3" @tap="onCopy(mallConfig.returnAddress)">
        退回地址：{{ mallConfig.returnAddress }}
      </view>
      <view class="flex" v-if="afterSaleStatus === 2 || afterSaleStatus === 3">
        退回物流单号：
        <input style="flex:1;" class="left_input" placeholder="填写退回物流单号" maxlength="40" v-model="lid" disabled="" />
      </view>
      <view class="flex" v-if="afterSaleStatus === 2">
        操作：
        <view @click="showModalInput" class="button_2 after_button">
          {{ afterSaleStatus === 2 ? '填写物流单号' : '更新物流单号' }}
        </view>
      </view>
      <view v-if="afterSaleStatus === 7">
        拒绝原因：{{ afterSalDetail.refuseReason }}
      </view>
    </view>
    <view class="invoice_bottom">
      <view v-if="afterSalDetail === null" @click="submit" class="button_2 invoice_bottom_btn">提交申请</view>
      <view v-if="afterSaleStatus === 7" @click="toReAfter" class="button_2 invoice_bottom_btn">重新申请</view>
      <view v-if="afterSaleStatus === 1 || afterSaleStatus === 2" @click="cancelAftersale"
        class="button_2 invoice_bottom_btn">取消申请</view>
      <view @click="cancel" style="background-color: #fff;" class="button_3 invoice_bottom_btn">返回</view>
    </view>
  </view>
</template>

<script>
import Big from "big.js";
import { order } from "../../services/index.js";
import { mapState } from "vuex";
import qs from "qs";
export default {
  data() {
    return {
      ajaxLoading: false,
      images: [],
      remark: '',
      afterSaleType: '',
      afterSalDetailAsync: false,
      afterSalDetail: null,
      afterSalDetailImages: [],
      totalCount: "",
      orderDetail: {},
      productId: '',
      selectProduct: {},
      productSquareUrl: "",
      afterSaleGoodStatus: 2,
      reAfterId: undefined,
      lid: '',
      afterSaleStatus: undefined,//后台返回的 售后状态
      info: {
        name: "",
      },
      range1: [
        { value: 1, text: "否" },
        { value: 2, text: "是" },
      ],
      range: [
        { value: 1, text: "普通退货" },
    //    { value: 2, text: "仅退款" },
        { value: 3, text: "换货" },
      ],
      reAfter: ''
    };
  },
  components: {},
  computed: {
    ...mapState(["mallConfig", "userToken", "flutterDone"]),
  },
  mounted() { },
  methods: {
    async getOrderDetail(orderNo, productId) {
      let res = await order.orderDetail({ orderNo });
      if (res.code === 200) {
        let temp = 0;
        let totalPrice = new Big(0);
        res.data.createTime = new Date(res.data.createTime * 1000).Format(
          "yyyy-MM-dd HH:mm:ss"
        );
        res.data.totalAmountFen = res.data.totalAmount;
        res.data.totalAmount = new Big(res.data.totalAmount).div(100);
        res.data.expressAmount = new Big(res.data.expressAmount).div(100);
        res.data.products.forEach((e) => {
          temp += e.count;
          e.payAmount = new Big(e.payAmount).div(100);
          e.price = new Big(e.price).div(100);
          totalPrice = totalPrice.plus(e.price.times(e.count)); //数量*价格
        });
        if (res.data.shipTime !== null) {
          res.data.shipTime = new Date(res.data.shipTime * 1000).Format(
            "yyyy-MM-dd HH:mm:ss"
          );
        }
        if (res.data.couponConfig !== null) {
          res.data.couponAmount = totalPrice
            .minus(res.data.totalAmount)
            .minus(res.data.expressAmount);
        }
        this.expressAmount = res.data.expressAmount;
        this.totalCount = temp;
        this.orderDetail = res.data;
        this.originPrice = totalPrice;
        this.productSquareUrl = res.data.products[0].productSquareUrl;
        this.selectProduct = res.data.products.find((e) => e.productId === productId);
      }
    },
    invoiceTypeChange(i) {
      // this.checkSame(i, this.invoiceInfo.titleType);
    },
    onLoad(params) {
      //轮训 flutterDone状态 如果为true则执行下面的方法 如果超过10秒则跳转到订单列表
      uni.showLoading();
      this.reAfter = params.reAfter;
      // #ifdef H5
      let count = 0;
      let timer = setInterval(() => {
        if (count > 10) {
          //跳转到订单列表
          clearInterval(timer);
          uni.navigateTo({
            url: "/pages/myOrder/index",
          });
        } else if (this.flutterDone || this.userToken !== null) {
          clearInterval(timer);
          if (params.afterSaleNo) {
            this.aftersaleDetail({ afterSaleNo: params.afterSaleNo });
          } else {
            this.aftersaleDetail({ orderNo: params.orderNo, productId: Number(params.productId) });
            this.getOrderDetail(params.orderNo, Number(params.productId));
            this.productId = Number(params.productId);
          }
        }
        count++;
      }, 1000);
      // #endif
      // #ifdef MP-WEIXIN 
      this.getOrderDetail(params.orderNo, Number(params.productId));
      this.aftersaleDetail({ orderNo: params.orderNo, productId: Number(params.productId) })
      this.productId = Number(params.productId);
      // #endif
      // this.getOrderDetail(params.orderNo, Number(params.productId));
      // this.aftersaleDetail(params.orderNo, Number(params.productId))
      // this.productId = Number(params.productId);
    },
    onShow() {
    },
    cancel() {
      uni.redirectTo({
        url: "/pages/myOrder/index",
      });
    },
    async handleSelect(res, index) {
      // #ifdef MP-WEIXIN 
      await this.uploadImg(res.tempFilePaths, index);
      // #endif

      // #ifdef H5
      await this.uploadImgNew(res.tempFilePaths, index);
      // #endif
    },
    async uploadImgNew(tempFilePaths, index) {
      if (!tempFilePaths.length) return;  //如果没有选择图片就退出
      const userToken = this.userToken;
      //循环选择图片的张数
      tempFilePaths.map(async () => {
        const path = tempFilePaths.pop();
        //因为我这个后台给的接口一次只能上传一张图片，所以每循环一次就调用接口上传一次
        let header = {
          Authorization: `Bearer ${userToken.token}`,
          'X-Client-Type': 'APP'
        }
        const [err, { data }] = await uni.uploadFile({
          url: '/api/file/upload',//后台地址
          filePath: path,
          //todo 需要判断状态
          header: header,
          formData: {
            'fileClassification': 'COMMENT',//可以附带的属性，我这里是用户的id
          },
          name: 'file',
        });
        //因为async返回的是个promise对象，所以要把返回的数据转为对象格式。
        let dataObj = JSON.parse(data)
        //每循环一次就把后台返回的图片地址添加到filePathsList数组
        this.images.push({
          url: dataObj.data,
          name: ""
        });

      })
      this.uploadImgNew(tempFilePaths, index);
    },
    async uploadImg(tempFilePaths, index) {
      if (!tempFilePaths.length) return;  //如果没有选择图片就退出
      const userToken = this.userToken;
      //循环选择图片的张数
      tempFilePaths.map(async () => {
        const path = tempFilePaths.pop();
        //因为我这个后台给的接口一次只能上传一张图片，所以每循环一次就调用接口上传一次
        let header = {
          Authorization: `Bearer ${userToken.token}`,
          'X-Client-Type': 'MINI_PROGRAM'
        }
        const [err, { data }] = await uni.uploadFile({
          url: 'https://www.realbook.com.cn/api/file/upload',//后台地址
          filePath: path,
          //todo 需要判断状态
          header: header,
          formData: {
            'fileClassification': 'COMMENT',//可以附带的属性，我这里是用户的id
          },
          name: 'file',
        });
        //因为async返回的是个promise对象，所以要把返回的数据转为对象格式。
        let dataObj = JSON.parse(data)
        //每循环一次就把后台返回的图片地址添加到filePathsList数组
        this.images.push({
          url: dataObj.data,
          name: ""
        });
        console.log(this.images);
      })
      this.uploadImg(tempFilePaths, index);
    },
    handleDelete(err, index) { // 删除图片
      //todo 全删除
      const num = this.images.findIndex(v => v === err.tempFilePath);
      this.images.splice(num, 1);
    },
    async submit() {
      let images = [];
      this.images.forEach((e) => {
        images.push(e.url);
      });
      let data = {
        id: this.reAfterId,
        orderNo: this.orderDetail.orderNo,
        afterSaleType: this.afterSaleType,
        afterSaleGoodStatus: this.afterSaleGoodStatus,
        productId: this.productId,
        images: images,
        remark: this.remark
      }
      if (this.afterSaleType === '') {
        uni.showToast({
          title: '请选择售后类型',
          icon: 'none'
        })
        return;
      }
      if (this.ajaxLoading) {
        return
      }
      this.ajaxLoading = true;
      uni.showLoading({
        title: '加载中'
      });
      let res = await order.aftersaleOrder(data);
      if (res.code === 200) {
        uni.showToast({
          title: '申请成功',
          icon: 'none',
          success: function () {
            setTimeout(() => {
              wx.navigateBack({
                //返回上一页
                delta: 1,
              });
            }, 1000);
          },
        });
        uni.hideLoading();
      } else {
        let errMsg = {
          2102: '已发货商品不支持仅退款，请申请普通退货'
        }
        let msg = errMsg[res.code] || res.msg;
        uni.showToast({
          title: msg,
          icon: 'none'
        })
      }
      this.ajaxLoading = false;
    },
    async aftersaleDetail({ orderNo, productId, afterSaleNo } = {}) {
      uni.showLoading({
        title: '加载中'
      });
      let res = await order.aftersaleDetail({ orderNo: orderNo, productId: productId, afterSaleNo });
      if (res.code === 200) {
        if (res.data !== null && this.reAfter != '1') {
          //\n1普通退货\n2补发\n3换货
          let afterSaleTypeName = ['', '普通退货', '补发', '换货'];
          //\n1买家已经申请退款，等待卖家同意\n2卖家已经同意退款，等待买家退货\n3买家已经退货，等待卖家确认收货\n4等待卖家退款\n5退款中\n6完成\n7关闭
          let afterSaleStatusName = ['', '买家已经申请退款，等待卖家同意', '卖家已经同意退款，等待买家退货', '买家已经退货，等待卖家确认收货', '等待卖家退款', '退款中', '售后单已完成', '售后单关闭', '等待卖家发货', '卖家已经发货，等待买家确认收货'];
          res.data.afterSaleTypeName = afterSaleTypeName[res.data.afterSaleType];
          res.data.afterSaleStatusName = afterSaleStatusName[res.data.afterSaleStatus];
          if (res.data.images) {
            this.afterSalDetailImages = JSON.parse(res.data.images);
          }
          res.data.refundAmount = new Big(res.data.refundAmount).div(100);
          this.afterSaleStatus = res.data.afterSaleStatus;
          // this.selectProduct = res.data.product;
          this.lid = res.data.lid || '';
          this.orderDetail = res.data;
        }
        if(this.reAfter != '1'){
          this.afterSalDetail = res.data;
        }else{
          this.reAfterId = res.data.id;
        }
        //如果是h5 请求订单详情接口
        // #ifdef H5
        if (res.data !== null) {
          if (afterSaleNo) {
            this.productId = res.data.productId;
          }
          this.getOrderDetail(res.data.orderNo, res.data.productId);
        }
        // #endif
      }
      uni.hideLoading();
    },
    showModalInput() {
      uni.showModal({
        title: '请填写退回物流单号',
        content: '',
        placeholderText: '请填写退回物流单号',
        editable: true,
        success: (res) => {
          if (res.confirm) {
            this.lid = res.content;
            this.lidModal(res.content);
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
    async lidModal(lid) {
      let regex = /^[a-zA-Z0-9]+$/;
      if (!regex.test(lid)) {
        uni.showToast({
          title: '请输入正确的物流单号',
          icon: 'none'
        })
        return;
      }
      uni.showLoading();
      let res = await order.aftersaleLogistics({ afterSaleNo: this.afterSalDetail.afterSaleNo, lid: lid });
      if (res.code === 200) {
        uni.showToast({
          title: '提交成功',
          icon: 'none'
        });
        this.aftersaleDetail({ orderNo: this.orderDetail.orderNo, productId: this.productId });
      } else {
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
      uni.hideLoading();
    },
    async cancelAftersale() {
      //是否确认取消售后申请
      uni.showModal({
        title: '提示',
        content: '是否确认取消售后申请',
        success: async (res) => {
          if (res.confirm) {
            let res = await order.cancelAftersale({ afterSaleNo: this.afterSalDetail.afterSaleNo });
            if (res.code === 200) {
              uni.showToast({
                title: '取消成功',
                icon: 'none',
                success: function () {
                  wx.navigateBack({
                    //返回上一页
                    delta: 1,
                  });
                },
              })
            } else {
              uni.showToast({
                title: res.msg,
                icon: 'none'
              })
            }
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
    onLookLogistics(item) {
      let data = {
        deliveryId: item.sellerLcId,
        lId: item.sellerLId,
        orderNo: item.orderNo,
        afterSaleNo: item.afterSaleNo,
        type: 'after',
      };
      let str = qs.stringify(data);
      uni.navigateTo({
        url: "/pages/logisticsDetails/index?" + str,
      });
    },
    async onUpdateOrder(item) {
      uni.showModal({
        title: '是否确认收货',
        confirmText: '确认',
        success: async function (res) {
          if (res.confirm) {
            uni.showLoading();
            let res = await order.aftersaleConfirm({
              afterSaleNo: item.afterSaleNo,
            });
            if (res.code === 200) {
              uni.showToast({
                title: '确认收货成功',
                icon: 'none',
                success: function () {
                  setTimeout(() => {
                    wx.navigateBack({
                      //返回上一页
                      delta: 1,
                    });
                  }, 1000);
                },
              });
            } else {
              uni.showToast({
                icon: 'none',
                title: res.msg
              });
            }
            uni.hideLoading();
          } else if (res.cancel) {
          }
        }
      })
    },
    toReAfter() {
      uni.redirectTo({
        url: `/pages/after/index?reAfter=1&orderNo=${this.orderDetail.orderNo}&productId=${this.productId}`
      });
    },
    onCopy(item) {
      uni.setClipboardData({
        data: item,
        success: function () {
        }
      });
    },
  },
};
</script>

<style scoped>
.invoice {
  min-height: 100vh;
  background-color: #F7F8FA;
  box-sizing: border-box;
  padding-bottom: 200rpx;
}

.img {
  width: 150rpx;
  height: 150rpx;
  margin-bottom: 5rpx;
}


.flex {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.order_info {
  margin: 25rpx auto 0;
  width: 90%;
  display: flex;
  border-radius: 20rpx;
  background-color: #fff;
  padding: 25rpx;
}

.order_img {
  margin-right: 20rpx;
}

.order_number {
  margin-bottom: 10rpx;
  word-break: break-all;
}

.money {
  color: rgba(242, 85, 0, 1);
  font-size: 40rpx;
}

.invoice_bottom {
  position: fixed;
  bottom: 0;
  width: 96%;
  margin: 0 auto;
  left: 0;
  right: 0;
  z-index: 100;
}

.invoice_bottom_btn {
  width: 100%;
  border-radius: 10rpx;
  margin-bottom: 15rpx;
  text-align: center;
  height: 80rpx;
  line-height: 80rpx;
}

.add_pic {
  width: 100%;
  height: 100%;
}

.textarea {
  width: 100%;
  height: 100rpx;
}

.after_pic {
  width: 100rpx;
  height: 100rpx;
  margin-right: 10rpx;
}

.after_button {
  width: 200rpx;
  border-radius: 10rpx;
  text-align: center;
  height: 60rpx;
  line-height: 60rpx;
}

.after_top {
  width: 100%;
  height: 256rpx;
  background: linear-gradient(90deg, #FF6146 0%, #FEC56E 100%);
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  border-bottom-left-radius: 30rpx;
  border-bottom-right-radius: 30rpx;
}

.after_top_tips_status {
  font-size: 34rpx;
  margin-bottom: 10rpx;
}

.my-orders-shop-item-control-btn {
  width: 173rpx;
  height: 62rpx;
  border-radius: 31rpx;
  text-align: center;
  font-size: 28rpx;
  line-height: 62rpx;
  margin-right: 30rpx;
}

.gray {
  border: 1rpx solid rgba(204, 204, 204, 1);
  color: #666;
}

.red {
  border: 1rpx solid rgba(242, 85, 0, 1);
  color: #f25500;
}

.after_logistics {
  display: flex;
  justify-content: flex-end;
  margin-top: 40rpx;
}
</style>
<style>
.uni-select {
  border: none !important;
}

.uni-select__input-text {
  font-size: 32rpx;
}

.uni-select__input-placeholder {
  font-size: 32rpx !important;
}
</style>
